using System.Threading.Tasks;
using GetKlient.Models;
using Microsoft.EntityFrameworkCore;

namespace GetKlient.Services
{
    public class MonitorHeartTempService
    {
        private readonly PFlibDbContext _dbContext;

        public MonitorHeartTempService(PFlibDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<Models.MonitorHeartTemp> GetMonitorHeartTemp(System.DateTime dStart)
        {
            try
            {
                return await _dbContext.MonitorHeartTemp.FirstOrDefaultAsync(m => m.DStart == dStart);
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"查询时出错：{ex.Message}");
            }
        }

        public async Task UpdateOrInsertMonitorHeartTemp(System.DateTime dStart, int nEnters, int nExits, string sDev)
        {
            try
            {
                var exists = await _dbContext.MonitorHeartTemp.AnyAsync(m => m.DStart == dStart);
                if (exists)
                {
                    await UpdateMonitorHeartTemp(dStart, nEnters, nExits, sDev);
                }
                else
                {
                    await InsertMonitorHeartTemp(dStart, nEnters, nExits, 0, 0, sDev);
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"更新或插入时出错：{ex.Message}");
            }
        }

        public async Task InsertMonitorHeartTemp(System.DateTime dStart, int nEnters, int nExits, int nPassings, int nReturns, string sDev)
        {
            try
            {
                var monitorHeartTemp = new Models.MonitorHeartTemp
                {
                    DStart = dStart,
                    NEnters = nEnters,
                    NExits = nExits,
                    NPassings = nPassings,
                    NReturns = nReturns,
                    SDev = sDev
                };
                _dbContext.MonitorHeartTemp.Add(monitorHeartTemp);
                await _dbContext.SaveChangesAsync();
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"插入时出错：{ex.Message}");
            }
        }

        public async Task UpdateMonitorHeartTemp(System.DateTime dStart, int nEnters, int nExits, string sDev)
        {
            try
            {
                var monitorHeartTemp = await _dbContext.MonitorHeartTemp.FirstOrDefaultAsync(m => m.DStart == dStart && m.SDev == sDev);
                if (monitorHeartTemp!= null)
                {
                    monitorHeartTemp.NEnters = nEnters;
                    monitorHeartTemp.NExits = nExits;
                    await _dbContext.SaveChangesAsync();
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"更新时出错：{ex.Message}");
            }
        }
    }
}